package com.jack006.article.html.controller;

import com.jack006.exception.GraceException;
import com.jack006.grace.result.ResponseStatusEnum;
import com.mongodb.client.gridfs.GridFSBucket;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * @Classname ArticleController
 * @Description 文章业务实现
 * @Date 2021-06-10 08:15
 * @Created by jack
 */
@Component
public class ArticleHtmlComponent {

    final static Logger logger = LoggerFactory.getLogger(ArticleHtmlComponent.class);

    @Autowired
    private GridFSBucket gridFSBucket;


    @Value("${freemarker.html.article}")
    private String articlePath;

    public Integer download(String articleId, String articleMongoId) throws Exception {
        if (StringUtils.isBlank(articleId)) {
            GraceException.display(ResponseStatusEnum.ARTICLE_ID_IS_NULL_ERROR);
        }
        if (StringUtils.isBlank(articleMongoId)) {
            GraceException.display(ResponseStatusEnum.ARTICLE_MONGO_ID_IS_NULL_ERROR);
        }
        // 拼接最终文件的保存的地址
        String path = articlePath + File.separator+articleId+".html";
        // 获取文件流，定义存放的位置和名称
        File file = new File(path);
        // 创建输出流
        OutputStream out = new FileOutputStream(file);
        // 执行下载
        gridFSBucket.downloadToStream(new ObjectId(articleMongoId),out);
        return HttpStatus.OK.value();
    }

    public Integer delete(String articleId) throws Exception {
        // 拼接最终文件的保存的地址
        String path = articlePath + File.separator + articleId + ".html";

        // 获取文件流，定义存放的位置和名称
        File file = new File(path);

        // 删除文件
        file.delete();

        return HttpStatus.OK.value();
    }
}
